const fs = require("fs");
const path = require("path");
const Cookie = require('./cookie');
const JSON = require('./JSON')

module.exports = {
    // 切割文件后缀名
    splitFileName: (text) => {
        let index = text.lastIndexOf(".");
        return {
            name: text.substring(0, index),
            suffix: text.substring(index + 1)
        };
    },
    // 递归创建目录
    mkdirsSync: (dirname) => {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (utils.mkdirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    },

    // 验证是否有token
    checkToken: () => async (ctx,next) => {
        if(!Cookie.checkoutCoolie(ctx,'token') && ctx.request.url!=='/hospital/login/loginCheck'){
            ctx.body = JSON.resultErrorJson('0002','用户未登录！');
        }
        await next();
    },
    // 创建菜单
    menuTree: (hospitalId, hospitalName, arr)=>{
        let menu = {
            hospitalId: hospitalId,
            hospitalName: hospitalName,
            includes: []
        };
        for (let item of arr) {
            check(menu.includes,item);
        }
        function check(includes,item){
            for(let citem of includes){
                if(citem.m_id == item.fm_id){
                    citem.child.push({
                        m_id: item.sm_id,
                        m_name: item.sm_name,
                        m_url: item.sm_url,
                        m_icon: item.sm_icon,
                    })
                    return;
                }
            }
            includes.push({
                m_id:item.fm_id,
                m_name:item.fm_name,
                m_icon:item.fm_icon,
                child:[{
                    m_id: item.sm_id,
                    m_name: item.sm_name,
                    m_url: item.sm_url,
                    m_icon: item.sm_icon,
                }]
            })
            return;
        }
        return menu;
    }
}